<?php

namespace App\Rep;

use App\Models\ExchangeGoods;
use App\Models\FinishProduct;
use App\Models\SemiFinishProduct;
use Illuminate\Support\Facades\DB;

class ExchangeGoodsRep
{

    /**
     * 获取换货列表
     * @param $params
     * @return void
     */
    public function getExchangeGoodsListRep($params){
        $list = ExchangeGoods::Search($params)->with(['semi'=>function($q){
            $q->with([
                'color',
                'product'=>function($q){
                    return $q->select('id','product_name');
                },
                'model_number',
                'specification',
                'models'
            ]);
        },'order'])->paginate($params['per_page']??10);
        return $list;
//        $finishRep = new FinishProductRep();
//        $params['logistics_status'] = 3;
//        $params['return_status'] = [0,2];
//        $list = $finishRep->getFinishProductListRep($params);
//        return $list;
    }

    /**
     * 新增换货
     * @param $params
     * @return array
     */
    public function exchangeGoodsRep($params){
        DB::beginTransaction();
        try{
            //当前半成品
            $semi = SemiFinishProduct::where('id',$params['semi_id'])->first();
            $finish_id = $semi->finish_id;

            $model = new ExchangeGoods();
            $model->order_id = $semi->order_id;
            $model->exchange_time = $params['exchange_time']??'';
            $model->remark = $params['remark'];
            $model->semi_id = $params['semi_id'];
            $model->num = $params['num'];
            $model->finish_id = $semi->finish_id;
            $semiRep = new SemiFinishProductRep();
            //从库存中随机取出
            $semi_id_arr = $semiRep->getInventoryIdRep($semi->product_id,$semi->model_number_id,$semi->specification_id,$warehouse_id,$goods_shelf_id);
            $key = array_rand($semi_id_arr);
            $val = $semi_id_arr[$key];
            $model->semi_id_now = $val;
            $model->save();
            $semi = SemiFinishProduct::where('id',$params['semi_id'])->update(['finish_id'=>'','is_del'=>2]);
            $semi_now = SemiFinishProduct::where('id',$val)->first();
            $semi_now->finish_id = $finish_id;
            $semi_now->is_del = 1;
            $semi_now->save();

            FinishProduct::where('order_id',$semi->order_id)->update(['return_status'=>2]);

            DB::commit();
            return ['code'=>0,'data'=>$model,'msg'=>'success'];
        }catch(\Exception $exception){
            DB::rollBack();
            return ['code'=>2001,'data'=>$params,'msg'=>$exception->getMessage()];
        }


    }
}
